<template>
  <a-card
    :body-style="{padding: '24px 32px'}"
    :bordered="false">
    <a-spin :spinning="loading">
      <a-form
        @submit="handleSubmit"
        :form="form">
        <a-form-item
          label="企业名称"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'enterpriseName',
              {rules: [{ required: true, message: '请输入企业名称' }]}
            ]"
            name="enterpriseName"
            placeholder="企业名称"
          />
        </a-form-item>
        <a-form-item
          label="用户名"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'enterpriseSimpleName',
              {rules: [{ required: true, message: '请输入用户名' }, {
                max: 10,
                message: '不超过10个字'
              }]}
            ]"
            name="enterpriseSimpleName"
            placeholder="用户名"
          />
        </a-form-item>
        <a-form-item
          label="邮箱"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'email',
              {rules: [{ required: true, type:'email', message: '请输入邮箱' }]}
            ]"
            name="email"
            placeholder="邮箱"
          />
        </a-form-item>
        <a-form-item
          label="联系人姓名"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'managerName',
              {rules: [{ required: false, message: '请输入联系人姓名' }]}
            ]"
            name="managerName"
            placeholder="联系人姓名"
          />
        </a-form-item>
        <a-form-item
          label="联系人手机号"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'managerPhone',
              {rules: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入联系人手机号' }]}
            ]"
            name="managerPhone"
            placeholder="联系人手机号"
          />
        </a-form-item>

        <a-form-item
          label="项目审核"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-radio-group
            v-decorator="['needAudit', {
              initialValue: false
            }]"
          >
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          label="合同扫描件"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <div v-if="form.getFieldValue('contractScanCopy')">
            <a @click="imageUrlPrefix +form.getFieldValue('contractScanCopy')">{{ form.getFieldValue('contractScanCopy') }}</a>
            <span>&nbsp;
              <a-icon
                type="close"
                @click="removeFile"
              /></span>
          </div>
          <a-upload
            v-else
            name="mediaFile"
            :showUploadList="false"
            :before-upload="beforeUploadFile"
          >
            <a-button :loading="uploadLoading">
              <a-icon type="upload" />添加
            </a-button>
          </a-upload>
          <a-input
            hidden
            v-decorator="[
              'contractScanCopy',
              {rules: [{ required: false, message: '请上传合同扫描件' }]}
            ]"
          />
        </a-form-item>


        <a-form-item
          label="账单方式"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-radio-group
            v-decorator="['feeMode', {
              initialValue: 2
            }]">
            <a-radio :value="1">开票金额</a-radio>
            <a-radio :value="2">实发金额</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="费率类型"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-radio-group
            v-decorator="['feeRateType', {
              initialValue: 1
            }]"
            @change="setFeeRateType"
          >
            <a-radio :value="1">固定</a-radio>
            <a-radio :value="2">阶梯</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="feeRateType === 1"
          label="服务费率"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input-number
            :min="1"
            :max="20"
            :step="1"
            :formatter="value => `${value}%`"
            :parser="value => value.replace('%', '')"
            placeholder="服务费率"
            style="width: 100%;"
            v-decorator="[
              'feeRate',
              {rules: [{ required: true, message: '请输入服务费率' }]}
            ]"
          />
        </a-form-item>
        <a-form-item
          v-if="feeRateType === 2"
          label="阶梯费率"
          required
          :help="feeRangeValidator.help"
          :validate-status="feeRangeValidator.status"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-table
            v-show="feeRateRangeList.length"
            :columns="feeRateRangeColumns"
            rowKey="amountLow"
            :pagination="false"
            :data-source="feeRateRangeList"
            size="small"
          >
            <span
              slot="money"
              slot-scope="text">
              <span>{{ text | formatMoney }}</span>
            </span>
            <span
              slot="rate"
              slot-scope="text">
              <span>{{ (text * 100).toFixed(2) }}%</span>
            </span>
            <span
              slot="action"
              slot-scope="text, record, index">
              <template v-if="index === 0 || (index + 1) === feeRateRangeList.length">
                <a @click="deleteFeeRangeRow(index)">删除</a>
              </template>
            </span>
          </a-table>
          <a-button
            type="primary"
            @click="showCollectionModel">新增费率</a-button>
          <collection-create-form
            ref="collectionForm"
            :visible="collectionFormVisable"
            @cancel="handleCollectionCancel"
            @create="handleCollectionCreate"
          />
        </a-form-item>
        <a-form-item
          label="在线支付"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-switch
            checked-children="开通"
            un-checked-children="关闭"
            v-decorator="[
              'isOpenXbd', {
                valuePropName: 'checked',
                initialValue: false
              }
            ]"
          />
        </a-form-item>
        <a-form-item
          v-if="form.getFieldValue('isOpenXbd')"
          label="xbdUserUuid"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'userUuid',
              {rules: [{ required: true, message: '请输入xbdUserUuid' }]}
            ]"
            name="userUuid"
          />
        </a-form-item>
        <a-form-item
          v-if="form.getFieldValue('isOpenXbd')"
          label="xbdToken"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[
              'userToken',
              {rules: [{ required: true, message: '请输入xbdToken' }]}
            ]"
            name="userToken"
          />
        </a-form-item>
        <a-form-item
          label="企业状态"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-radio-group
            v-decorator="['status', {
              initialValue: 1
            }]">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">冻结</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center">
          <a-button
            htmlType="submit"
            type="primary">立即{{ pageTypeName }}</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import { addEnterprise, updateEnterprise, getEnterpriseDetail, uploadProjectFile } from '@/api/manage'
import CollectionCreateForm from './feeRange-Form'
import config from '@/config/defaultSettings'
import NP from 'number-precision'

export default {
  name: 'EnterpriseAdd',
  components: { CollectionCreateForm },
  data() {
    return {
      // description: '表单页用于向用户收集或验证信息，基础表单常见于数据项较少的表单场景。',
      form: this.$form.createForm(this),
      imageUrlPrefix: config.uploadedUrlPrefix,
      defaultFileList: [],
      uploadLoading: false,
      value: 1,
      feeRateType: 1,
      collectionFormVisable: false,
      feeRateRangeList: [],
      feeRangeValidator: {
        status: 'success'
      },
      feeRateRangeColumns: [
        {
          title: '最低金额',
          dataIndex: 'amountLow',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: '最高金额',
          dataIndex: 'amountHigh',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: '服务费率',
          dataIndex: 'feeRate',
          scopedSlots: { customRender: 'rate' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loading: false
    }
  },
  computed: {
    pageTypeName: function() {
      let name = ''
      if (this.$route.params.enterpriseId) {
        name = '修改'
        this.getDetail(this.$route.params.enterpriseId)
      } else {
        name = '创建'
        this.resetForm()
      }
      return name
    }
  },
  methods: {
    //上传合同扫描件
     beforeUploadFile(file) {
      // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      console.log(file)
      this.file = file
      this.defaultFileList.push(file)
      // if (!isJpgOrPng) {
      //   this.$message.error('只能上传JPG或PNG图片！')
      // }
      // const isLt2M = file.size / 1024 / 1024 < 10
      // if (!isLt2M) {
      //   this.$message.error('图片需小于10M')
      // }
      // if (isJpgOrPng && isLt2M) {
      //   this.handleFileUpload('projectAttachment')
      // }
      this.handleFileUpload('contractScanCopy')
      console.log(contractScanCopy)
      return false
    },
    handleFileUpload(fieldName) {
      const formData = new FormData()
      formData.append('mediaFile', this.file)
      this.uploadLoading = true
      uploadProjectFile(formData).then(res => {
        const filename = res.resData && res.resData.result
        this.form.setFieldsValue({
          [fieldName]: filename
        })
      }).catch(() => {
        this.defaultFileList = []
        this.$message.error('上传失败，请重试')
      }).finally(() => {
        this.uploadLoading = false
      })
    },
    removeFile() {
      this.defaultFileList = []
      this.form.resetFields('contractScanCopy')
    },


    getDetail(enterpriseId) {
      this.loading = true
      getEnterpriseDetail(enterpriseId)
        .then(res => {
          this.setFieldsData(res.resData)
        })
        .finally(() => {
          this.loading = false
        })
    },
    setFieldsData(data) {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          enterpriseName: data.enterpriseName,
          enterpriseSimpleName: data.enterpriseSimpleName,
          managerName: data.managerName,
          managerPhone: data.managerPhone,
          email: data.email,
          needAudit: data.needAudit,
          contractScanCopy: data.contractScanCopy,
          feeMode: data.feeMode,
          feeRateType: data.feeRateType,
          feeRate: data.feeRate && NP.times(data.feeRate,100),
          isOpenXbd: data.isOpenXbd,
          status: data.status
        })
        if (data.isOpenXbd) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              userUuid: data.xbdConfig && data.xbdConfig.userUuid,
              userToken: data.xbdConfig && data.xbdConfig.userToken
            })
          })
        }
        this.feeRateType = data.feeRateType
        this.feeRateRangeList = data.feeRateRangeList || []
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.checkFeeRange()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.$route.params.enterpriseId) {
            values.enterpriseId = this.$route.params.enterpriseId
          }
          if (values.feeRateType === 1) {
            values.feeRate = NP.divide(values.feeRate,100)
          } else {
            values.feeRate = null
            values.feeRateRangeList = this.feeRateRangeList
          }
          console.log('Received values of form: ', values)
          this.doSubmit(values)
        }
      })
    },
    doSubmit(values) {
      const postMethod = this.$route.params.enterpriseId ? updateEnterprise : addEnterprise
      this.loading = true
      postMethod(values)
        .then(res => {
          console.log(res)
          this.$message.success(`${this.pageTypeName}成功`)
          this.$router.push('/enterprise/list')
        })
        .catch(err => {
          console.log(err)
          this.$message.error(`${this.pageTypeName}失败`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    showCollectionModel() {
      this.collectionFormVisable = true
    },
    handleCollectionCancel() {
      this.$refs.collectionForm.form.resetFields()
      this.collectionFormVisable = false
    },
    handleCollectionCreate() {
      const form = this.$refs.collectionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        const arrayLength = this.feeRateRangeList.length
        if (
          arrayLength &&
          values.amountHigh * 100 !== this.feeRateRangeList[0].amountLow &&
          values.amountLow * 100 !== this.feeRateRangeList[arrayLength - 1].amountHigh
        ) {
          this.$message.error('请确保费率区间连续')
          return
        }
        // console.log('Received values of form: ', values)
        values.amountHigh *= 100
        values.amountLow *= 100
        values.feeRate = NP.divide(values.feeRate,100)
        this.feeRateRangeList.push(values)
        this.feeRateRangeList.sort((a, b) => a.amountLow - b.amountLow)
        form.resetFields()
        this.checkFeeRange()
        this.collectionFormVisable = false
      })
    },
    deleteFeeRangeRow(index) {
      this.feeRateRangeList.splice(index, 1)
      this.checkFeeRange()
    },
    setFeeRateType(event) {
      this.feeRateType = event.target.value
    },
    checkFeeRange() {
      if (this.feeRateRangeList.length) {
        this.feeRangeValidator = {
          help: '',
          status: 'success'
        }
      } else {
        this.feeRangeValidator = {
          help: '请添加阶梯费率',
          status: 'error'
        }
      }
    },
    resetForm() {
      this.form.resetFields()
    }
  }
}
</script>
